package com.cspg.ssss.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.config.WeixinProperties;
import com.cspg.ssss.domain.DepartmentEntity;
import com.cspg.ssss.domain.UserDepartmentEntity;
import com.cspg.ssss.domain.UserEntity;
import com.cspg.ssss.repository.DepartmentUserRepository;
import com.cspg.ssss.util.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SyncOrgUserService {
    @Autowired
    WxDepartmentService wxDepService;

    @Autowired
    DepartmentUserRepository repository;

    @Autowired
    WeixinService wxService;

    @Autowired
    WeixinProperties wxProperties;

    /**
     * 根据部门ID获取部门下所有子部门，如果部门ID=-1，则获取所有部门列表
     *
     * @param did 部门id
     */
    private JSONObject getDepartmentsList(int did) {
        String token = wxService.getToken(wxProperties.getCorpid(), wxProperties.getSecret());
        String getUrl = wxProperties.getUrlroot() + "/cgi-bin/department/list?access_token=" + token;
        if (did > 0) {
            getUrl += "&id=" + String.valueOf(did);
        }
        return HttpRequest.httpsGetRequest(getUrl);
    }

    /**
     * 根据部门ID获取部门下所有人员列表
     *
     * @param did        部门id
     * @param fetchChild 是否获取子部门人员 1-获取 0-不获取
     */
    private JSONObject getUserListByDepartmentId(int did, int fetchChild) {
        String token = wxService.getToken(wxProperties.getCorpid(), wxProperties.getSecret());
        String getUrl = wxProperties.getUrlroot() + "/cgi-bin/user/list?access_token=" + token + "&department_id=" + String.valueOf(did) + "&fetch_child=" + String.valueOf(fetchChild);
        return HttpRequest.httpsGetRequest(getUrl);
    }

    /**
     * 从elink同步所有部门信息
     *
     * @return
     */
    private void syncDepartments() {
        JSONObject retObj = getDepartmentsList(-1);
        JSONArray array = retObj.getJSONArray("department");
        repository.truncateDepart();
        for (int i = 0; i < array.size(); i++) {
            DepartmentEntity en = new DepartmentEntity();
            JSONObject obj = array.getJSONObject(i);
            en.setId(obj.getInteger("id"));
            en.setDepartment_name(obj.getString("name"));
            en.setPid(obj.getInteger("parentid"));
            en.setOrder(obj.getInteger("order"));
            en = getDepartmentPathJsonArray(en, array);
            //en.setDepartment_path("");
            //en.setDepartment_name("");
            repository.insertDepartment(en);
        }
    }

    private DepartmentEntity getDepartmentPath(DepartmentEntity en, List<DepartmentEntity> allList) {
        String department_path = String.valueOf(en.getId());
        String department_pathname = en.getDepartment_name();
        int curid = en.getPid();
        boolean bBreak = false;
        while (!bBreak) {
            boolean bHaveparent = false;
            for (DepartmentEntity tmp : allList) {
                if (curid == tmp.getId()) {
                    department_path = String.valueOf(curid) + "/" + department_path;
                    department_pathname = tmp.getDepartment_name() + "/" + department_pathname;
                    curid = tmp.getPid();
                    bHaveparent = true;
                    break;
                }
            }

            if (!bHaveparent) {
                bBreak = true;
            }
        }
        en.setDepartment_path(department_path);
        en.setDepartment_pathname(department_pathname);
        return en;
    }

    private DepartmentEntity getDepartmentPathJsonArray(DepartmentEntity en, JSONArray allList) {
        String department_path = String.valueOf(en.getId());
        String department_pathname = en.getDepartment_name();
        int curid = en.getPid();
        boolean bBreak = false;
        while (!bBreak) {
            boolean bHaveparent = false;
            for (int i = 0; i < allList.size(); i++) {
                JSONObject obj = allList.getJSONObject(i);
                if (curid == obj.getInteger("id")) {
                    department_path = String.valueOf(curid) + "/" + department_path;
                    department_pathname = obj.getString("name") + "/" + department_pathname;
                    curid = obj.getInteger("parentid");
                    bHaveparent = true;
                    break;
                }
            }
            if (!bHaveparent) {
                bBreak = true;
            }
        }
        en.setDepartment_path(department_path);
        en.setDepartment_pathname(department_pathname);
        return en;
    }

    /**
     * 从elink同步所有人员信息
     */
    private void syncUserInfo() {
        JSONObject retObj = getUserListByDepartmentId(1, 1);
        JSONArray array = retObj.getJSONArray("userlist");
        repository.truncateUser();
        repository.truncateDepartUser();
        for (int i = 0; i < array.size(); i++) {
            UserEntity entity = new UserEntity();
            JSONObject obj = array.getJSONObject(i);

            entity.setUser_id(obj.getString("userid"));
            entity.setUser_name(obj.getString("name"));
            entity.setMobile(obj.getString("mobile"));
            entity.setEmail(obj.getString("email"));

            repository.insertUser(entity);
            JSONArray departArr = obj.getJSONArray("department");
            List<Integer> list = JSONArray.parseArray(departArr.toJSONString(), Integer.class);
            for (Integer integer : list) {
                UserDepartmentEntity udEntity = new UserDepartmentEntity();
                udEntity.setDepart_id(integer);
                udEntity.setUser_id(entity.getUser_id());
                repository.insertUserDepartment(udEntity);
            }
        }
    }

    /**
     * 清空数据后同步组织机构和人员
     *
     * @return
     */
    public void syncDepartmentAndUsers() {
        syncDepartments();
        syncUserInfo();
    }
}
